package com.sparrow.source.common.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author bryceyung
 * @since 2024/12/2
 */
@Component
public class RedisUtils {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 将值放入缓存
     */
    public void set(String key, Object value) {
        stringRedisTemplate.opsForValue().set(key, String.valueOf(value));
    }

    /**
     * 字符串：取对象
     */
    public <T> T getObject(String key) {
        Object o = stringRedisTemplate.opsForValue().get(key);
        if (o != null) {
            return (T) o;
        }
        return null;
    }

    /**
     * 将值放入缓存并设置时间-秒
     */
    public void set(String key, Object value, long time) {
        if (time > 0) {
            stringRedisTemplate.opsForValue().set(key, String.valueOf(value), time, TimeUnit.SECONDS);
        } else {
            stringRedisTemplate.opsForValue().set(key, String.valueOf(value));
        }
    }

    /**
     * 删除key
     */
    public void deleteKey(String key) {
        stringRedisTemplate.delete(key);
    }

    /**
     * 删除keys
     *
     * @param keys
     */
    public void deleteKeyGroup(List<String> keys) {
        stringRedisTemplate.delete(keys);
    }

    /**
     * 上锁
     *
     * @param key
     * @param value
     * @param releaseTime
     * @return
     */
    public boolean lock(String key, Object value, long releaseTime) {
        //        // 尝试获取锁
        //        Boolean boo = redisTemplate.opsForValue().setIfAbsent(key, value, releaseTime, TimeUnit.SECONDS);
        //        // 判断结果
        //        return boo != null && boo;
        //java 使用redis的事务时不能直接用Api中的multi()和exec()，这样multi()和exec()两次使用的stringRedisTemplate不是一个connect，会导致死锁

        SessionCallback<Boolean> sessionCallback = new SessionCallback<Boolean>() {
            List<Object> exec = null;

            @Override
            @SuppressWarnings("unchecked")
            public Boolean execute(RedisOperations operations) throws DataAccessException {
                operations.multi();
                stringRedisTemplate.opsForValue().setIfAbsent(key, String.valueOf(value));
                stringRedisTemplate.expire(key, releaseTime, TimeUnit.SECONDS);
                exec = operations.exec();
                if (exec.size() > 0) {
                    return (Boolean) exec.get(0);
                }
                return false;
            }
        };
        return stringRedisTemplate.execute(sessionCallback);
    }

}
